
$NG.AllReady(function (
    page,
    { useAction, useBeforeClick, useValuesChange, useUpdateRows, useDataIndexChange, useClick }
) {
    const mstform = $NG.getCmpApi("p_form_cost_apply_rep_syb");
    const grid = $NG.getCmpApi("p_form_cost_apply_rep_d_syb");

    if (page.oType == "add") {
        var pc = mstform.getItem("phid_pc")
        if (pc.getValue() > '0') {

            pcinfo(pc.getValue())
            setTitle()
        }

        mstform.getItem("u_phid_fcur").setValue({
            value: 1,
            label: "人民币",
        });
        mstform.getItem("u_exchangerate").setValue(1)
    }

    //项目名称变化时自动带入产品线、事业部
    useValuesChange(({ args }) => {
        console.log(args[0]);

        const phid_pc = args[0].phid_pc.value;
        //从项目取值
        if (phid_pc) {
            console.log(phid_pc);
            pcinfo(phid_pc)
            setTitle()
        }

    }, "p_form_cost_apply_rep_syb.phid_pc");

    useUpdateRows(({ args, table }) => {
        sumAmtD()
        // grid.updateRow(rows);
    }, 'p_form_cost_apply_rep_d_syb');

    

    useDataIndexChange(({ args }) => {
        const record = args[0];
        console.log(record)

        record.u_amt_bcsq = record.u_bcwsje * (1 + record.u_taxrate)
        grid.updateRow(args[0]);
    }, "u_bcwsje");

    useBeforeClick(async function ({ args }) {
        // 按钮点击前事件
        const grid = $NG.getCmpApi("p_form_cost_apply_rep_d_syb");
        const rows = grid.getRows();

        for (let i = 0; i < rows.length; i++) {
            const restAmtVat = rows[i].u_rest_amt; // 剩余金额
            const applyAmt = rows[i].u_amt_bcsq;  // 申请金额
            const subName = rows[i].u_sub_name;   // 分包项名称

            // 校验：剩余金额是否小于申请金额
            if (restAmtVat < applyAmt) {
                $NG.alert(`${subName} 超出设备清单该分包项金额，请修改`);
                return false; // 阻止按钮后续操作
            }
        }

        // 如果所有行都通过校验，返回 true
        return true;
    }, "save");


    cntDFilter();
    function cntDFilter() {
        $NG.updateUI((updater) =>
            updater.editGrid.p_form_cost_apply_rep_d_syb.u_cost_pc.setProps((p) => {
                return {
                    ...p,
                    editor: {
                        ...p.editor,
                        clientSqlFilter: ("phid in('8570000000000328')")
                    },
                };
            })
        );
    }
    // 表头计算
    function sumAmtD(){
        const rows = grid.getRows()
        
        var sumAmt = 0;
        var sumAmt1 = 0;
        rows.forEach(item => {
            
            item.u_bcwsje = (1 - (Number(item.u_taxrate) || 0)) * (Number(item.u_amt_bcsq) || 0)
            item.u_taxamt = item.u_amt_bcsq - item.u_bcwsje

            if (item.u_bcwsje) {
                sumAmt += parseFloat(item.u_bcwsje);  //明细

            }
            if (item.u_amt_bcsq) {
                sumAmt1 += parseFloat(item.u_amt_bcsq);  //明细

            }

            
        })
        //汇总赋值到表头字段
        $NG.updateState((updater) => {
            updater.data.p_form_cost_apply_rep_syb.setProps({
                amt: sumAmt,  //表头：
                u_amt_vat: sumAmt1,  //表头：
            });
        });
        grid.refreshView()
    }

});
function setTitle() {
    var pcname = $NG.getCmpApi("p_form_cost_apply_rep_syb").getItem("phid_pc").getRawValue().BillName;
    var dt = $NG.getCmpApi("p_form_cost_apply_rep_syb").getItem("bill_dt").getValue();
    $NG.getCmpApi("p_form_cost_apply_rep_syb").getItem("bill_name").setValue(pcname + dt + '费用申请')
}

function pcinfo(pcvalue) {
    const grid = $NG.getCmpApi("p_form_cost_apply_rep_d_syb");

    $NG.execServer('getPtInfoByPhid', { phid: pcvalue }, function (res) {
        const datas = JSON.parse(res.data)[0].extendObjects;
        console.log(datas);
        $NG.updateState((updater) => {
            //【注意这里的表名不能为控件ID，必须要是表名】
            updater.data.p_form_cost_apply_rep_syb.setProps({
                phid_emp: {
                    value: datas.project_manager_phid,
                    label: datas.project_manager_name,
                },
                u_division: {
                    value: datas.division_phid,
                    label: datas.division_name,
                },
                phid_org: {
                    value: datas.org_phid,
                    label: datas.org_name,
                },
                u_regional_center: {
                    value: datas.regional_center_phid,
                    label: datas.regional_center_name,
                },
                u_product_line: {
                    value: datas.midwife_phid,
                    label: datas.midwife_name,
                },
            });
        });
    });


    $NG.execServer('GetSbUnforeseeable_Info', { pc: pcvalue }, function (res) {
        if (res.count == 0) return;
        const data = JSON.parse(res.data);
        var gridArr = [];
        var gridCount = res.count;

        for (var i = 0; i < gridCount; i++) {
            // 列出需要赋值的表体字段
            var gridObj = {
                u_cost_pc: '',
                u_bcwsje: '',
                u_amt_bcsq: '',
                u_rest_amt: '',
                u_gs_days: '',
                u_taxamt: '',
                u_taxrate: '',
            };
            
            gridObj.u_rest_amt = data[i].extendObjects.u_unforeseeable_syzd,
                gridObj.u_cost_pc = '8570000000000328',
                gridObj.u_cost_pc_EXName = '实施费用-招待费',
                gridObj.u_taxrate = 0,
                gridObj.u_taxamt = 0,
                gridArr.push(gridObj);
        }
        grid.clearRows();
        grid.addRows(gridArr);
        grid.refreshView();
    });
}